module Support where

import Char
import Data.List

{- Utilità testo -}

isCloseParenthesis :: Char -> Bool
isCloseParenthesis c = c `elem` ")]}"

isParenthesis :: Char -> Bool
isParenthesis c = c `elem` "()[]{}"

isUpperString :: String -> Bool
isUpperString = and . map isUpper

isQuote :: Char -> Bool
isQuote c = c == '"' || c == '\''

isEndl :: Char -> Bool
isEndl = ('\n'==)

isEmptyLine :: String -> Bool
isEmptyLine cs = rest == ""
  where
    (_, rest) = span isSpace cs

spanRight :: (a -> Bool) -> [a] -> ([a], [a])
spanRight pred xs = (reverse prefix, reverse suffix)
  where
    (prefix, suffix) = span pred $ reverse xs

trimLeft :: String -> String
trimLeft = snd . span isSpace

trimRight :: String -> String
trimRight = snd . spanRight isSpace

trim :: String -> String
trim = trimLeft . trimRight

stripLeft :: String -> String
stripLeft = snd . span (' '==)

chompLeft :: String -> String
chompLeft = snd . span ('\n'==)

takeLast :: [a] -> ([a], a)
takeLast xs = (ys, y)
  where
    (ys, [y]) = splitAt (length xs - 1) xs

indentLines :: Int -> [String] -> [String]
indentLines n ls = map f ls
  where
    f line = indent ++ line
    indent = take n $ repeat ' '

indentText :: Int -> String -> String
indentText n = intercalate "\n" . indentLines n . lines

{- Tree -}

data Tree a = Void
            | Node a [Tree a]
            deriving Show

leaf :: a -> Tree a
leaf x = Node x []

{- Utilità funzionali -}

apply :: a -> (a -> b) -> b
apply x f = f x

{- Lists -}

safehead :: [a] -> Maybe a
safehead (x:_) = Just x
safehead _     = Nothing